﻿using System;
using System.Web;
using System.Xml;

namespace Sherwood.Web
{
    public class QueryParameter
    {
        private string _dictionaryKey;
        private string _encodedKey;
        private string _encodedValue;
        private string _key;
        private string _value;

        public QueryParameter(string raw)
        {
            RawKeyAndValue = raw;
        }

        public QueryParameter(string key, string value)
        {
            if (key == null) throw new ArgumentNullException("key");
            Key = key;
            Value = value;
        }

        public string RawKeyAndValue
        {
            get { return EncodedKey + "=" + EncodedValue; }
            set
            {
                string[] s = value.Split(new[] {'='}, 2);
                EncodedKey = s[0];
                EncodedValue = s.Length < 2 ? string.Empty : s[1];
            }
        }

        public string EncodedValue
        {
            get { return _encodedValue; }
            set
            {
                _encodedValue = value;
                _value = HttpUtility.UrlDecode(_encodedValue);
            }
        }

        public string EncodedKey
        {
            get { return _encodedKey; }
            set
            {
                _encodedKey = value;
                _key = HttpUtility.UrlDecode(_encodedKey);
            }
        }

        public string DictionaryKey
        {
            get { return _dictionaryKey ?? Key.ToLowerInvariant(); }
            set { _dictionaryKey = value; }
        }

        public string Key
        {
            get { return _key; }
            private set
            {
                _key = value;
                _encodedKey = HttpUtility.UrlEncode(_key);
            }
        }

        public string Value
        {
            get { return _value; }
            set
            {
                _value = value;
                _encodedValue = HttpUtility.UrlEncode(_value);
            }
        }

        public DateTime ValueAsDate
        {
            get { return XmlConvert.ToDateTime(Value, XmlDateTimeSerializationMode.Utc); }
            set { Value = XmlConvert.ToString(value, XmlDateTimeSerializationMode.Utc); }
        }

        public Guid ValueAsGuid
        {
            get { return new Guid(Value); }
            set { Value = value.ToString(); }
        }

        public int ValueAsInt
        {
            get { return int.Parse(Value); }
            set { Value = value.ToString(); }
        }
    }
}